/**
 * Canvas implementation.
 */

#include "Canvas.h"

/////////////////////////////////////////////////

kig::Canvas::Canvas(unsigned int w, unsigned int h) : _width(w), _height(h), _drops(0)
{
	ASSERT(_width > 0 && _height > 0);
	_drops = (kig::Drop*) calloc(_width*_height, sizeof(Drop));
	ASSERT(_drops);
}

/////////////////////////////////////////////////

kig::Drop* kig::Canvas::operator()(unsigned int x, unsigned int y)
{
	ASSERT(x<_width && y<_height);
	return &(_drops[y*_width+x]);
}

/////////////////////////////////////////////////

kig::Canvas::~Canvas()
{
	if (_drops) {
		free(_drops);
	}
}

/////////////////////////////////////////////////

void kig::Canvas::dumpToPPM(std::ostream& os)
{
	unsigned int max=256;
	os << "P3" << std::endl;
	os << "# generated by kig" << std::endl;
	os << getWidth() << " " << getHeight() << std::endl;
	os << max << std::endl;
	
	// TODO clamp values!
	// TODO binary PPM
	for (unsigned int y=0; y<getHeight(); ++y) {
		for (unsigned int x=0; x<getWidth(); ++x) {
			kig::Drop* d = (*this)(x,y);
			kig::Vec4 c;
			std::vector<kig::Vec4>::iterator iter;
			for (iter=d->samples.begin(); iter!=d->samples.end(); ++iter) {
				c[0] += (*iter)[0];
				c[1] += (*iter)[1];
				c[2] += (*iter)[2];
			}
			c /= d->samples.size();
			os << (unsigned int)(256 * c[0]) << " ";
			os << (unsigned int)(256 * c[1]) << " ";
			os << (unsigned int)(256 * c[2]) << std::endl;
		}
	}
}

/////////////////////////////////////////////////

std::string kig::Canvas::getDesc() const
{
	std::stringstream s;
	s << "Standard canvas, " << _width << "x" << _height;
	return s.str();
}



